package com.bootssm.controller;

import com.bootssm.pojo.PageView;
import com.bootssm.pojo.User;
import com.bootssm.pojo.UserVO;
import com.bootssm.service.UserService;
import com.bootssm.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/findAll")
    public PageView<User> findAll(@RequestBody UserVO userVO) {
        Integer page=userVO.getPage();
        Integer start=(page-1)*userVO.getSize();
        userVO.setStart(start);
        List<User> userlist = userService.findAll(userVO);
        Integer count=userService.getCount(userVO);
        PageView<User> pageView=new PageView<>();
        pageView.setDataList(userlist);
        pageView.setCount(count);
        return pageView;
    }

    @PostMapping("/addAll")
    public Result insertUser(@RequestBody User user) {
        try {
           userService.insertUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("500", "插入失败");
        }
        return new Result("200", "插入成功");
    }

    @PostMapping("/login")
    public Result Login(@RequestBody User user) {
        int i;
        try {
            i = userService.login(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("500", "登录失败，账号或密码错误");
        }
        System.out.println(i);
        if (i > 0) {
            return new Result("200", "登录成功");
        } else {
            return new Result("500", "登录失败，账号或密码错误");

        }

    }

    @GetMapping("/deleteUser/{userId}")
    public Result deleteUser(@PathVariable("userId") String userId) {
        /*
         *根据id删除
         */
        try {
            userService.deleteUser(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("500", "删除失败");
        }
        return new Result("200", "删除成功");
    }

    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody User user) {
        /*
         *根据id删除
         */
        try {
            userService.updateUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("500", "修改失败");
        }
        return new Result("200", "修改成功");
    }

    @GetMapping("/findById/{userId}")
    public User findById(@PathVariable("userId") String userId) {
        User user = userService.findById(userId);
        return user;
    }
}
